package windows

import (
	"github.com/asticode/go-astilectron"
	bootstrap "github.com/asticode/go-astilectron-bootstrap"
	"go_gui_basic_binding/frame/appOptions"
	"go_gui_basic_binding/frame/bind"
)

func Create(tmp, name string, windowOptions *astilectron.WindowOptions, openDevTools ...bool) (*astilectron.Window, error) {
	var err error
	a := appOptions.Astilectron
	var w *astilectron.Window
	if w, err = a.NewWindow("resources/app/"+tmp+".html", windowOptions); err != nil {
		return nil, err
	}
	w.OnMessage(func(m *astilectron.EventMessage) (v interface{}) {
		// Unmarshal message
		var iMsg bootstrap.MessageIn
		var err error
		if err = m.Unmarshal(&iMsg); err != nil {
			return
		}
		switch iMsg.Name {
		case "go_func":
			bind.Run(iMsg.Payload)
		default:
		}
		return nil
	})
	err = w.Create()
	if err != nil {
		return nil, err
	}

	w.On(astilectron.EventNameWindowEventClosed, func(e astilectron.Event) (deleteListener bool) {
		delete(appOptions.Cw, name)
		return
	})

	if len(openDevTools) > 0 {
		if openDevTools[0] {
			_ = w.OpenDevTools()
		}
	}
	appOptions.Cw[name] = w
	return nil, err
}
